import { Injectable } from '@nestjs/common';
import * as moment from 'moment';
import * as path from 'path';
import * as fs from 'fs';

const host = 'http://localhost:3000';

@Injectable()
export class UploadService {
  private readonly uploadPath = path.join(process.cwd(), 'public/image');

  private readonly publicPath = '/static/image';

  public uploadImage(file: Express.Multer.File) {
    const date = new Date();

    const month = date.getMonth() + 1;
    const filePath = path.join(this.uploadPath, month.toString());
    const fileName =
      moment().format('YYYY-MM-DD') +
      '-' +
      date.getTime() +
      path.extname(file.originalname);

    if (!fs.existsSync(filePath)) {
      fs.mkdirSync(filePath);
    }

    fs.writeFileSync(path.join(filePath, fileName), file.buffer);

    return {
      ossUrl: host + path.join(this.publicPath, month.toString(), fileName),
    };
  }
}
